<template>
    <div class="container">
        <div class="map-container" id="map-container"></div>

        <div class="search-container">
            <el-input
                clearable
                v-model="searchText"
                class="w-50 m-2"
                placeholder="输入地址关键字搜索"
                :prefix-icon="Search"
                @change="search"
            />
            <div class="res-list-container" v-if="showSearchRes">

                <span class="loading">
                    <el-button v-if="searchedLoading" loading type="text"></el-button>
                </span>

                <span class="no-data" v-if="!searchedLoading && searchedList.length == 0" >无数据</span>

                <template v-if="searchedList && searchedList.length > 0">
                    <div class="item" v-for="(item, index) in searchedList" :key="index" :class="item == selectedItem?'selected':''" @click="selectItem(item)">
                        <div class="address">
                            <span class="district">{{item.district || ''}}</span>
<!--                            <span class="address">{{item.address || ''}}</span>-->
                            <span class="name">{{item.name || ''}}</span>
                        </div>
                    </div>
                </template>

            </div>
        </div>

    </div>
</template>

<script setup>

import {onBeforeUnmount, onMounted, ref} from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import LocationIcon from "../../../assets/images/location.png";
import {  Search } from '@element-plus/icons-vue'
const map = ref(null);
const props = defineProps(['lat', 'lon'])
const marker = ref(null);

const searchText = ref('');
const selectedItem = ref({});
const searchedList = ref([]);
const searchedLoading = ref(false);
const houseMarker = ref({})
const showSearchRes = ref(false)

let _AMap = null;

onMounted(() => {
    initMap().then(() => {
            if (props.lat && props.lon) {
                showMarker();
            }
        }
    );
})

onBeforeUnmount(()=>{
    map.value.clearEvents();
})

//搜索
const search = ()=>{
    if (!searchText.value){
        searchedList.value = [];
        showSearchRes.value = false;
        return;
    }
    showSearchRes.value = true;
    searchedLoading.value = true;

    AMap.plugin('AMap.AutoComplete', function(){
        let autoOptions = {
            city: '全国'
        };
        // 实例化AutoComplete
        let autoComplete= new AMap.AutoComplete(autoOptions);
        // 根据关键字进行搜索
        autoComplete.search(searchText.value, function(status, result) {
            searchedLoading.value = false;

            // 搜索成功时，result即是对应的匹配数据
            if (result && result.tips){
                searchedList.value = result.tips || [];
            }else {
                searchedList.value = [];
                return;
            }
            for (let tip of result.tips) {
                let location = tip.location;
                if (location){
                    tip.lon = location.lng;
                    tip.lat = location.lat;
                }
            }

        })
    })

}


const selectItem = (item)=>{
    selectedItem.value = item;
    let lon = item.lon;
    let lat = item.lat;
    let address = item.district + item.address + item.name;

    showMarker(lon, lat);

    map.value.setFitView(marker.value, true);

    emit('addressSelected', item);
}

const showMarker = (lon, lat) => {
    if (marker.value){
        map.value.remove(marker.value)
    }
    marker.value = new AMap.Marker({
        position: new AMap.LngLat(lon || props.lon, lat || props.lat),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        anchor: 'bottom-center',
        icon: new AMap.Icon({
            image: LocationIcon,
            size: [36, 36],
            imageSize: [36, 36],
        }),
    });
    map.value.add(marker.value)

}

const emit = defineEmits(["mapClick"]);
const onMapClick = (e)=>{
   let lon = e.lnglat.lng;
   let lat = e.lnglat.lat;
   showMarker(lon, lat);

   emit('mapClick', {lon, lat});
}

//初始化地图
const initMap = () => {
    return new Promise((resolve, reject) => {
        AMapLoader.load({
            key: "9c4d1e3eb0c12d91bb25ccaae913615a",             // 申请好的Web端开发者Key，首次调用 load 时必填
            version: "2.0",      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
            plugins: [''],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        }).then((AMap) => {
            _AMap = AMap;
            map.value = new AMap.Map("map-container", {  //设置地图容器id
                viewMode: "3D",    //是否为3D地图模式
                zoom: 11,           //初始化地图级别
                center: [props.lon || 121.310626, props.lat || 31.915724], //初始化地图中心点位置
            });

            map.value.on('click', onMapClick);

            resolve();
        }).catch(e => {
            console.log(e);
        })
    })

}

</script>

<style scoped lang="scss">
.container {
    width: 100%;
    height: 100%;
    background: #1ab394;
    position: relative;

    > .map-container {
        width: 100%;
        height: 100%;
    }

    .search-container{
        width: 40%;
        //background: #fff;
        //box-shadow: 0 0 5px #2d5cf622;
        position: absolute;
        left: 10px;
        top: 10px;
        //padding: 10px;

        >.res-list-container{
            width: 100%;
            max-height: 260px;
            background: #fff;
            margin-top: 10px;
            border-radius: 5px;
            box-shadow: 0 0 5px #2d5cf622;
            padding: 10px;
            overflow: auto;

            >.no-data, .loading{
                width: 100%;
                color: #999;
                text-align: center;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            >.item{
                display: flex;
                color: #444;
                padding: 10px 5px;
                cursor: pointer;
                transition: 0.15s;
                >.address{
                    //font-weight: bold;
                    span{
                        margin-right: 10px;
                    }
                    span:last-child{
                        margin-right: 0;
                    }
                }
                >.head-name{
                }
            }
            >.item:hover{
                background: #88b9f9;
                color: #fff;
            }
            >.item:active{
                background: #5a9cf8;
                color: #fff;
            }
            >.item.selected{
                background: #5a9cf8;
                color: #fff;
            }
        }
    }
}
</style>
